<?php

/**
 * 追加投放计划的加油包
 * 当计划天数剩余一半时（向下取整），检测流量执行情况，当完成度少于50%时，再次追加1个加油包。
 * 每天检查一次（0点检查）
 */

ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\bizAd\AdPlan as mAdPlan;
use Biz\model\bizAd\AdPlanDataFlow as mAdPlanDataFlow;
use Biz\service\bizAd\AdPlan;

$now = time();
$where = [
    'start_time[<]' => $now,
    'end_time[>]' => $now,
    'settle_status' => mAdPlan::SETTLE_STATUS_NORMAL,
    'expose_count[<]' => \Medoo\Medoo::raw('`target_count`'),
    'plan_status' => mAdPlan::PLAN_STATUS_OPEN,
];
$list = mAdPlan::getPlanList($where);

foreach ($list as $row) {
    $planId = $row['id'];
    $startDay = date('Y-m-d', $row['start_time']);
    $endDay = date('Y-m-d', $row['end_time']);
    $middleDayTime = getMiddleDayTime($startDay, $endDay);
    $now = time();
    $finishRate = ($row['expose_count'] > 0) ? ($row['expose_count'] / $row['target_count']) : 0;
    if ($now >= $middleDayTime && $row['target_count'] > $row['expose_count'] && $finishRate <= 0.5) {
        $flowCount = mAdPlanDataFlow::count(['plan_id' => $planId]);
        if ($flowCount == 1) {
            var_dump('追加流量包，计划id:' . $planId);
            //追加一个加油包
            $row['start_time'] = time();
            AdPlan::createFlow($row, mAdPlanDataFlow::TYPE_APPEND);
        }
    }
}

function getMiddleDayTime($startDay, $endDay)
{
    $planDay = (strtotime($endDay) - strtotime($startDay)) / 86400;
    $planDay = floor($planDay);
    $middle = ceil($planDay / 2);
    $middleDayTime = strtotime($startDay) + $middle * 86400 - 1;
    return $middleDayTime;
}